import urllib2
from struct import unpack
from datetime import datetime

#link="http://f17.yucache.net/users/c3d10055d7bc4d3fbf5ffc0a1eea55f8/texhnolyze-22.flv?file_type=video/x-flv&hash=6faacbf3ab2c09846e6ec61067ca34e0&file_size=40392127&start=0"
link="http://www.mediacollege.com/video-gallery/testclips/barsandtone.flv"

tagtypes={8:"Audio",9:"Video",18:"Meta",0:"Undefined"}

def read24bit(data,offset):
	b1, b2, b3 = unpack('3B', data[offset:offset+3])
	return (b1 << 16) + (b2 << 8) + b3

def readint(data,offset):
	return unpack('>I', data[offset:offset+4])[0]

def readbyte(data,offset):
	return unpack('B', data[offset:offset+1])[0]


def readAMFDouble(self):
	return unpack('>d', self.file.read(8))[0]

def readAMFBoolean(self):
	return self.readbyte() == 1

def readAMFString(self):
	size = self.readshort()
	return self.file.read(size)

def readAMFObject(self):
	data = self.readAMFMixedArray()
	result = object()
	result.__dict__.update(data)
	return result

def readAMFMixedArray(self):
	size = self.readint()
	result = {}
	for i in range(size):
		key = self.readAMFString()
		dataType = self.readbyte()
		if not key and dataType == 9:
			break
		result[key] = self.readAMFData(dataType)
	return result

def readAMFArray(self):
	size = self.readint()
	result = []
	for i in range(size):
		result.append(self.readAMFData)
	return result

def readAMFDate(self):
	return datetime.fromtimestamp(self.readAMFDouble())
        


def read_tag(data,offset):
	previoussize=readint(data,offset)
	tagtype=tagtypes[readbyte(data,offset+4)]
	datasize=read24bit(data,offset+5)
	timestamp =read24bit(data,offset+8)
	extendedtimestamp=readbyte(data,offset+11)
	streamid=read24bit(data,offset+12)
	return (previoussize,tagtype,datasize,timestamp,extendedtimestamp,streamid)

#link="http://www.wikidebrouillard.org/images/0/06/Test.flv"
req = urllib2.Request(link)
## read header + useful first tag
req.headers['Range'] = 'bytes=%s-%s' % (0, 23)
f = urllib2.urlopen(req)
hdr=f.read()
signature= hdr[0:3]
version= readbyte(hdr,3)
typeflags= readbyte(hdr,4)
dataoffset=readint(hdr,5)
extraheader=hdr[dataoffset:9]
print read_tag(hdr,dataoffset)


print signature
print version
print typeflags
print dataoffset
print extraheader
